package com.example.sunmiv1.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.AddGoodsSkuAdapterTest;
import com.example.sunmiv1.adapter.SkuGoodsAdapter;
import com.example.sunmiv1.entity.SkuGoodsInfo;
import com.example.sunmiv1.entity.SkuInfo;
import com.example.sunmiv1.utils.imgutils.BitmapCompressor;
import com.example.sunmiv1.utils.imgutils.UploadImg;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.example.sunmiv1.views.MyListView;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddGoodsActivityTest extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.addGoods_barcode_edit)
    EditText addGoodsBarcodeEdit;
    @BindView(R.id.addGoods_barcode_iv)
    ImageView addGoodsBarcodeIv;
    @BindView(R.id.addGoods_freightNumber)
    EditText addGoodsFreightNumber;
    @BindView(R.id.addGoods_name)
    EditText addGoodsName;
    @BindView(R.id.addGoods_price)
    EditText addGoodsPrice;
    @BindView(R.id.addGoods_purchasePrice)
    EditText addGoodsPurchasePrice;
    @BindView(R.id.addGoods_classification)
    LinearLayout addGoodsClassification;
    @BindView(R.id.addGoods_stock)
    EditText addGoodsStock;
    @BindView(R.id.addGoods_earlyWarning)
    EditText addGoodsEarlyWarning;
    @BindView(R.id.addGoods_excessQuantity)
    EditText addGoodsExcessQuantity;
    @BindView(R.id.addGoods_sure)
    TextView addGoodsSure;
    @BindView(R.id.addGoods_classification_name)
    TextView addGoodsClassificationName;
    @BindView(R.id.ll_choose_picture)
    LinearLayout llChoosePicture;
    @BindView(R.id.take_picture)
    TextView takePicture;
    @BindView(R.id.choose_picture)
    TextView choosePicture;
    @BindView(R.id.svMenu)
    ScrollView svMenu;
    @BindView(R.id.rlMenu)
    RelativeLayout rlMenu;
    @BindView(R.id.goods_picture)
    ImageView goodsPicture;
    @BindView(R.id.addGoods_is_change_weight)
    Switch addGoodsIsChangeWeight;
    @BindView(R.id.addGoods_is_sku)
    Switch addGoodsIsSku;
    @BindView(R.id.addGoods_is_skuLin)
    LinearLayout addGoodsIsSkuLin;
    @BindView(R.id.addGoods_addSku)
    TextView addGoodsAddSku;
    @BindView(R.id.addGoods_skuInner)
    LinearLayout addGoodsSkuInner;
    @BindView(R.id.addGoods_skuCancel)
    TextView addGoodsSkuCancel;
    @BindView(R.id.addGoods_skuConfirm)
    TextView addGoodsSkuConfirm;
    @BindView(R.id.addGoods_skuLin)
    LinearLayout addGoodsSkuLin;
    @BindView(R.id.addGoods_skuListView)
    ListView addGoodsSkuListView;
    @BindView(R.id.addGoods_skuGoodsListView)
    MyListView addGoodsSkuGoodsListView;
    @BindView(R.id.addGoods_skuGoodsLin)
    LinearLayout addGoodsSkuGoodsLin;
    @BindView(R.id.addGoods_skuGoodsView)
    View addGoodsSkuGoodsView;

    private Context context;
    private Intent intent;
    private String classId = "";
    private ACache aCache;
    private LoadingDialog loadingDialog;

    private String imgPath = "";

    private int is_change_weight = 1;//1:非稱重商品，2:稱重商品

    private int is_sku = 1;//1:單規格商品，2:多規格商品
    private SkuInfo skuInfo;
    private List<SkuInfo> skuInfoList = new ArrayList<>();
    private AddGoodsSkuAdapterTest addGoodsSkuAdapter;

    //Byron
    public static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    public static final int CHOOSE_PHOTO = 2;
    private Uri imageUri;
    private static final String TAG = "AddGoodsActivity";
    private List<SkuGoodsInfo> skuGoodsList = new ArrayList<>();
    private SkuGoodsAdapter skuGoodsAdapter;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Toast.makeText(context, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 99:
                    loadingDialog.dismiss();
                    Toast.makeText(context, "上傳失敗請重試", Toast.LENGTH_SHORT).show();
                    break;
                case 100:
                    loadingDialog.dismiss();
                    JSONObject json = null;
                    try {
                        json = new JSONObject((String) msg.obj);
                        if (json.getInt("status") == 1) {
                            imgPath = json.getString("path");
                            Looper.prepare();
                            Toast.makeText(context, "上傳成功", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        } else {
                            Looper.prepare();
                            Toast.makeText(context, "請重新上傳", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_add_goods_test);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.addGoods);
        setEdit(addGoodsPrice);
        setEdit(addGoodsPurchasePrice);
        setEdit(addGoodsStock);
        setEdit(addGoodsEarlyWarning);
        setEdit(addGoodsExcessQuantity);
        addGoodsIsChangeWeight.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                addGoodsIsSkuLin.setVisibility(View.GONE);
                is_change_weight = 2;
            } else {
                addGoodsIsSku.setChecked(false);
                addGoodsIsSkuLin.setVisibility(View.VISIBLE);
                is_change_weight = 1;
            }
        });
        addGoodsIsSku.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                is_sku = 2;
                addGoodsSkuLin.setVisibility(View.VISIBLE);
            } else {
                is_sku = 1;
                addGoodsSkuLin.setVisibility(View.GONE);
                addGoodsSkuGoodsLin.setVisibility(View.GONE);
                addGoodsSkuGoodsView.setVisibility(View.GONE);
                skuGoodsList.clear();
                setSkuGoodsAdapter();
                skuInfoList.clear();
                setAddGoodsSkuAdapter();
            }
        });
        getSkuList();
    }

    private void setAddGoodsSkuAdapter() {
        if (addGoodsSkuAdapter == null) {
            addGoodsSkuAdapter = new AddGoodsSkuAdapterTest(context, skuInfoList);
            addGoodsSkuListView.setAdapter(addGoodsSkuAdapter);
        } else {
            addGoodsSkuAdapter.notifyDataSetChanged();
        }
        if (skuInfoList.size() == 4) {
            addGoodsAddSku.setVisibility(View.GONE);
        } else {
            addGoodsAddSku.setVisibility(View.VISIBLE);
        }
        addGoodsSkuAdapter.Click(new AddGoodsSkuAdapterTest.Operation() {
            @Override
            public void delete(int position) {
                skuInfoList.remove(position);
                setAddGoodsSkuAdapter();
            }

            @Override
            public void addClass(int position, String className) {
                addSkuClass(position, className);
            }

            @Override
            public void addSku(int position, int classIndex, String id, String skuName) {
                addSkuName(position, classIndex, id, skuName);
            }

            @Override
            public void refreshHeight() {
                Log.e(TAG, "refreshHeight: 刷新高度");
                getTotalHeightListView(addGoodsSkuListView);

            }
        });
        Log.e(TAG, "setAddGoodsSkuAdapter: 設置適配器");
        getTotalHeightListView(addGoodsSkuListView);
    }

    private void setSkuGoodsAdapter() {
        skuGoodsAdapter = new SkuGoodsAdapter(context, skuGoodsList,false);
        addGoodsSkuGoodsListView.setAdapter(skuGoodsAdapter);
    }

    private int getTotalHeightListView(ListView listView) {
        ListAdapter mAdapter = listView.getAdapter();
        if (mAdapter == null) {
            return 0;
        }
        int totalHeight = 0;
        for (int i = 0; i < mAdapter.getCount(); i++) {
            View mView = mAdapter.getView(i, null, listView);
            mView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            //mView.measure(0, 0);
            Log.e("數據" + i, String.valueOf(mView.getMeasuredHeight()));
            totalHeight += mView.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
        Log.e("數據", "總高度=" + params.height);
        listView.setLayoutParams(params);
        listView.requestLayout();
        return totalHeight;
    }

    @OnClick({R.id.title_back, R.id.addGoods_barcode_iv, R.id.addGoods_classification, R.id.addGoods_sure,
            R.id.ll_choose_picture, R.id.take_picture, R.id.choose_picture, R.id.svMenu, R.id.rlMenu,
            R.id.addGoods_addSku, R.id.addGoods_skuCancel, R.id.addGoods_skuConfirm, R.id.addGoods_skuLin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.addGoods_addSku:
                if (skuInfoList.size() > 0) {
                    for (int i = 0; i < skuInfoList.get(0).getData().get(0).getList().size(); i++) {
                        Log.e(TAG, "onItemSelected: name5=" + skuInfoList.get(0).getData().get(0).getList().get(i).getName() +
                                skuInfoList.get(0).getData().get(0).getList().get(i).isChecked());
                    }
                }
                skuInfoList.add(new SkuInfo(skuInfo));
                for (int i = 0; i < skuInfoList.get(0).getData().get(0).getList().size(); i++) {
                    Log.e(TAG, "onItemSelected: name3=" + skuInfoList.get(0).getData().get(0).getList().get(i).getName() +
                            skuInfoList.get(0).getData().get(0).getList().get(i).isChecked());
                }
                setAddGoodsSkuAdapter();
                break;
            case R.id.addGoods_skuCancel:
                addGoodsSkuLin.setVisibility(View.GONE);
                addGoodsIsSku.setChecked(false);
                skuInfoList.clear();
                setAddGoodsSkuAdapter();
                addGoodsSkuGoodsLin.setVisibility(View.GONE);
                addGoodsSkuGoodsView.setVisibility(View.GONE);
                break;
            case R.id.addGoods_skuConfirm:
                addGoodsSkuLin.setVisibility(View.GONE);
                skuGoodsList.clear();
                int index = 0;
                switch (skuInfoList.size()) {
                    case 0:
                        addGoodsSkuGoodsLin.setVisibility(View.GONE);
                        addGoodsSkuGoodsView.setVisibility(View.GONE);
                        break;
                    case 1:
                        index = 0;
                        SkuInfo.DataBean.ListBean listBean0;
                        for (int i = 0; i < skuInfoList.get(0).getData().get(Integer.parseInt(skuInfoList.get(0).getDataIndex())).getList().size(); i++) {
                            listBean0 = skuInfoList.get(0).getData().get(Integer.parseInt(skuInfoList.get(0).getDataIndex())).getList().get(i);
                            Log.e(TAG, "onViewClicked: listBean0.check=" + listBean0.isChecked());
                            if (listBean0.isChecked()) {
                                index++;
                                String number = TextUtils.isEmpty(addGoodsFreightNumber.getText().toString().trim()) ?
                                        "" : addGoodsFreightNumber.getText().toString().trim() + "-" + index;
                                List<String> list1 = new ArrayList<>();
                                list1.add(listBean0.getId());
                                List<String> list2 = new ArrayList<>();
                                list2.add(listBean0.getName());
                                skuGoodsList.add(new SkuGoodsInfo(list1, list2,
                                        number, "", addGoodsPurchasePrice.getText().toString().trim(),
                                        addGoodsPrice.getText().toString().trim(), ""));
                            }
                        }
                        break;
                    case 2:
                        index = 0;
                        SkuInfo.DataBean.ListBean listBean1;
                        SkuInfo.DataBean.ListBean listBean2;
                        for (int i = 0; i < skuInfoList.get(0).getData().get(Integer.parseInt(skuInfoList.get(0).getDataIndex())).getList().size(); i++) {
                            listBean1 = skuInfoList.get(0).getData().get(Integer.parseInt(skuInfoList.get(0).getDataIndex())).getList().get(i);
                            if (listBean1.isChecked()) {
                                for (int s = 0; s < skuInfoList.get(1).getData().get(Integer.parseInt(skuInfoList.get(1).getDataIndex())).getList().size(); s++) {
                                    listBean2 = skuInfoList.get(1).getData().get(Integer.parseInt(skuInfoList.get(1).getDataIndex())).getList().get(s);
                                    if (listBean2.isChecked()) {
                                        index++;
                                        String number = TextUtils.isEmpty(addGoodsFreightNumber.getText().toString().trim()) ?
                                                "" : addGoodsFreightNumber.getText().toString().trim() + "-" + index;
                                        List<String> list1 = new ArrayList<>();
                                        list1.add(listBean1.getId());
                                        list1.add(listBean2.getId());
                                        List<String> list2 = new ArrayList<>();
                                        list2.add(listBean1.getName());
                                        list2.add(listBean2.getName());
                                        skuGoodsList.add(new SkuGoodsInfo(list1, list2,
                                                number, "", addGoodsPurchasePrice.getText().toString().trim(),
                                                addGoodsPrice.getText().toString().trim(), ""));
                                    }
                                }
                            }
                        }
                        break;
                    case 3:
                        index = 0;
                        SkuInfo.DataBean.ListBean listBean3;
                        SkuInfo.DataBean.ListBean listBean4;
                        SkuInfo.DataBean.ListBean listBean5;
                        for (int i = 0; i < skuInfoList.get(0).getData().get(Integer.parseInt(skuInfoList.get(0).getDataIndex())).getList().size(); i++) {
                            listBean3 = skuInfoList.get(0).getData().get(Integer.parseInt(skuInfoList.get(0).getDataIndex())).getList().get(i);
                            if (listBean3.isChecked()) {
                                for (int s = 0; s < skuInfoList.get(1).getData().get(Integer.parseInt(skuInfoList.get(1).getDataIndex())).getList().size(); s++) {
                                    listBean4 = skuInfoList.get(1).getData().get(Integer.parseInt(skuInfoList.get(1).getDataIndex())).getList().get(s);
                                    if (listBean4.isChecked()) {
                                        for (int t = 0; t < skuInfoList.get(2).getData().get(Integer.parseInt(skuInfoList.get(2).getDataIndex())).getList().size(); t++) {
                                            listBean5 = skuInfoList.get(2).getData().get(Integer.parseInt(skuInfoList.get(2).getDataIndex())).getList().get(t);
                                            if (listBean5.isChecked()) {
                                                index++;
                                                String number = TextUtils.isEmpty(addGoodsFreightNumber.getText().toString().trim()) ?
                                                        "" : addGoodsFreightNumber.getText().toString().trim() + "-" + index;
                                                List<String> list1 = new ArrayList<>();
                                                list1.add(listBean3.getId());
                                                list1.add(listBean4.getId());
                                                list1.add(listBean5.getId());
                                                List<String> list2 = new ArrayList<>();
                                                list2.add(listBean3.getName());
                                                list2.add(listBean4.getName());
                                                list2.add(listBean5.getName());
                                                skuGoodsList.add(new SkuGoodsInfo(list1, list2,
                                                        number, "", addGoodsPurchasePrice.getText().toString().trim(),
                                                        addGoodsPrice.getText().toString().trim(), ""));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    case 4:
                        index = 0;
                        SkuInfo.DataBean.ListBean listBean6;
                        SkuInfo.DataBean.ListBean listBean7;
                        SkuInfo.DataBean.ListBean listBean8;
                        SkuInfo.DataBean.ListBean listBean9;
                        for (int i = 0; i < skuInfoList.get(0).getData().get(Integer.parseInt(skuInfoList.get(0).getDataIndex())).getList().size(); i++) {
                            listBean6 = skuInfoList.get(0).getData().get(Integer.parseInt(skuInfoList.get(0).getDataIndex())).getList().get(i);
                            if (listBean6.isChecked()) {
                                for (int s = 0; s < skuInfoList.get(1).getData().get(Integer.parseInt(skuInfoList.get(1).getDataIndex())).getList().size(); s++) {
                                    listBean7 = skuInfoList.get(1).getData().get(Integer.parseInt(skuInfoList.get(1).getDataIndex())).getList().get(s);
                                    if (listBean7.isChecked()) {
                                        for (int t = 0; t < skuInfoList.get(2).getData().get(Integer.parseInt(skuInfoList.get(2).getDataIndex())).getList().size(); t++) {
                                            listBean8 = skuInfoList.get(2).getData().get(Integer.parseInt(skuInfoList.get(2).getDataIndex())).getList().get(t);
                                            if (listBean8.isChecked()) {
                                                for (int w = 0; w < skuInfoList.get(3).getData().get(Integer.parseInt(skuInfoList.get(3).getDataIndex())).getList().size(); w++) {
                                                    listBean9 = skuInfoList.get(3).getData().get(Integer.parseInt(skuInfoList.get(3).getDataIndex())).getList().get(w);
                                                    if (listBean9.isChecked()) {
                                                        index++;
                                                        String number = TextUtils.isEmpty(addGoodsFreightNumber.getText().toString().trim()) ?
                                                                "" : addGoodsFreightNumber.getText().toString().trim() + "-" + index;
                                                        List<String> list1 = new ArrayList<>();
                                                        list1.add(listBean6.getId());
                                                        list1.add(listBean7.getId());
                                                        list1.add(listBean8.getId());
                                                        list1.add(listBean9.getId());
                                                        List<String> list2 = new ArrayList<>();
                                                        list2.add(listBean6.getName());
                                                        list2.add(listBean7.getName());
                                                        list2.add(listBean8.getName());
                                                        list2.add(listBean9.getName());
                                                        skuGoodsList.add(new SkuGoodsInfo(list1, list2,
                                                                number, "", addGoodsPurchasePrice.getText().toString().trim(),
                                                                addGoodsPrice.getText().toString().trim(), ""));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
                setSkuGoodsAdapter();
                if (skuGoodsList.size() > 0) {
                    addGoodsSkuGoodsLin.setVisibility(View.VISIBLE);
                    addGoodsSkuGoodsView.setVisibility(View.VISIBLE);
                } else {
                    addGoodsSkuGoodsLin.setVisibility(View.GONE);
                    addGoodsSkuGoodsView.setVisibility(View.GONE);
                }
                break;
            case R.id.addGoods_skuLin:
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.addGoods_barcode_iv:
                startQrCode();
                break;
            case R.id.addGoods_classification:
                intent = new Intent(context, ClassificationActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.addGoods_sure:
                if ("".equals(addGoodsFreightNumber.getText().toString())) {
                    Toast.makeText(context, "請輸入商品貨號", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(addGoodsName.getText().toString())) {
                    Toast.makeText(context, "請輸入商品名稱", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(addGoodsPrice.getText().toString()) || Double.parseDouble(addGoodsPrice.getText().toString()) <= 0) {
                    Toast.makeText(context, "請輸入正確的價格", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(addGoodsPurchasePrice.getText().toString())) {
                    Toast.makeText(context, "請輸入商品進價", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(classId)) {
                    Toast.makeText(context, "請選擇分類", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(addGoodsStock.getText().toString())) {
                    Toast.makeText(context, "請輸入正確的商品庫存", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(addGoodsEarlyWarning.getText().toString())) {
                    Toast.makeText(context, "請輸入商品預警值", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(addGoodsExcessQuantity.getText().toString())) {
                    Toast.makeText(context, "請輸入商品超量值", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (is_sku == 2) {
                    if (skuGoodsList.size() == 0) {
                        Toast.makeText(context, "請重新選擇規格信息", Toast.LENGTH_SHORT).show();
                    } else {
                        for (int i = 0; i < skuGoodsList.size(); i++) {
                            if (TextUtils.isEmpty(skuGoodsList.get(i).getFreightNumber())) {
                                addGoodsSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                                return;
                            }
                            if (TextUtils.isEmpty(skuGoodsList.get(i).getPurchasePrice())) {
                                addGoodsSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                                return;
                            }
                            if (TextUtils.isEmpty(skuGoodsList.get(i).getPrice()) || Double.parseDouble(skuGoodsList.get(i).getPrice()) <= 0) {
                                Toast.makeText(context, skuGoodsList.get(i).getName() + "的售價不正確", Toast.LENGTH_SHORT).show();
                                addGoodsSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                                return;
                            }
                            if (TextUtils.isEmpty(skuGoodsList.get(i).getStock())) {
                                Toast.makeText(context, skuGoodsList.get(i).getName() + "的庫存不能爲空", Toast.LENGTH_SHORT).show();
                                addGoodsSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                                return;
                            }
                        }
                    }
                }
                addGood();
                break;
            case R.id.ll_choose_picture:
                rlMenu.setVisibility(View.VISIBLE);
                break;
            case R.id.take_picture:
                requestPermission();
                rlMenu.setVisibility(View.GONE);
                break;
            case R.id.choose_picture:
                //選擇圖片
                choosePhoto();
                rlMenu.setVisibility(View.GONE);
                break;
            case R.id.svMenu:
                break;
            case R.id.rlMenu:
                rlMenu.setVisibility(View.GONE);
                break;
        }
    }

    private File newFile;
    private String filePath = "";

    /*獲取權限*/
    private void requestPermission() {
//        Toast.makeText(context, "更新了嗎", Toast.LENGTH_SHORT).show();
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.CAMERA);
        }

        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(AddGoodsActivityTest.this, permissions, 1);
        } else {
            Log.e(TAG, "requestPermission: 所有權限獲取成功");
            openCamera(AddGoodsActivityTest.this);
        }
    }

    /*選擇圖片*/
    private void choosePhoto() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(AddGoodsActivityTest.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            openAlbum();
        }
    }

    private void openAlbum() {
        intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);//打開相冊
    }

    String data = "";

    /*上傳圖片*/
    private void upLoad() {
        loadingDialog.show();
        Toast.makeText(context, "正在上傳圖片，請稍等。。。。", Toast.LENGTH_SHORT).show();
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                data = UploadImg.uploadFile(newFile, Common.UPLOAD_IMG, jsonObject);
                Log.e(TAG, "run: " + data);
                if (data != null) {
                    Message msg = new Message();
                    msg.obj = data;
                    msg.what = 100;
                    handler.handleMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.what = 99;
                    handler.handleMessage(msg);
                }
            }
        }).start();

    }

    /*添加商品*/
    private void addGood() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));//門店id
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));//商戶id
            jsonObject.put("goods_name", addGoodsName.getText().toString());//商品名稱
            jsonObject.put("purch_price", addGoodsPurchasePrice.getText().toString());//商品進價
            jsonObject.put("goods_code", addGoodsBarcodeEdit.getText().toString());//商品條碼
            jsonObject.put("goods_number", addGoodsFreightNumber.getText().toString());//商品貨號
            jsonObject.put("goods_class_id", classId);//商品分類id
            jsonObject.put("retail_price", addGoodsPrice.getText().toString());//零售價
            jsonObject.put("goods_num", addGoodsStock.getText().toString());//庫存
            jsonObject.put("more_num", addGoodsExcessQuantity.getText().toString());//超量值
            jsonObject.put("less_num", addGoodsEarlyWarning.getText().toString());//預警值
            jsonObject.put("is_change_weight", is_change_weight);//是否是稱重商品,1:非稱重商品，2:稱重商品
            jsonObject.put("attribute_state", is_sku);
            jsonObject.put("goodimage", imgPath);
            if ("1".equals(aCache.getAsString("usertype"))) {
                jsonObject.put("usertype", 1);
            }
            jsonObject.put("skuList", new Gson().toJson(skuGoodsList));
            HttpUtils.post(context, Common.ADD_GOOD, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        loadingDialog.dismiss();
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            imgPath = "";
                            goodsPicture.setImageResource(R.mipmap.add_img);
                            addGoodsName.setText("");//商品名稱
                            addGoodsPurchasePrice.setText("");//商品進價
                            addGoodsBarcodeEdit.setText("");//商品條碼
                            addGoodsFreightNumber.setText("");//商品貨號
                            classId = "";//商品分類id
                            addGoodsClassificationName.setText("");
                            addGoodsPrice.setText("");//零售價
                            addGoodsStock.setText("");//庫存
                            addGoodsExcessQuantity.setText("");//超量值
                            addGoodsEarlyWarning.setText("");//預警值


                            is_change_weight = 1;
                            is_sku = 1;
                            addGoodsIsChangeWeight.setChecked(false);
                            addGoodsIsSku.setChecked(false);
                            skuGoodsList.clear();
                            setAddGoodsSkuAdapter();
                            addGoodsSkuGoodsLin.setVisibility(View.GONE);
                            addGoodsSkuGoodsView.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*添加規格分類名稱*/
    private void addSkuClass(int index, String name) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("name", name);
            HttpUtils.post(context, Common.ADD_SKU_ATTR, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            List<SkuInfo.DataBean> sku1 = skuInfoList.get(index).getData();
                            sku1.add(new SkuInfo.DataBean(json.getString("id"), name, true, new ArrayList<>()));
                            skuInfoList.get(index).setData(sku1);
                            skuInfoList.get(index).setDataIndex((skuInfoList.get(index).getData().size() - 1) + "");
                            setAddGoodsSkuAdapter();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*添加規格名稱*/
    private void addSkuName(int position, int classIndex, String id, String name) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("attr_id", id);
            jsonObject.put("name", name);
            HttpUtils.post(context, Common.ADD_SKU_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            List<SkuInfo.DataBean.ListBean> sku1 = skuInfoList.get(position).getData().get(classIndex).getList();
                            sku1.add(new SkuInfo.DataBean.ListBean(json.getString("id"), name, true));
                            skuInfoList.get(position).getData().get(classIndex).setList(sku1);
                            setAddGoodsSkuAdapter();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    /*權限回調*/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(context, "必須同意所有權限才能使用本程序", Toast.LENGTH_SHORT).show();
//                            finish();
                            return;
                        }
                        openCamera(AddGoodsActivityTest.this);
                    }
                } else {
                    Toast.makeText(context, "發生未知錯誤", Toast.LENGTH_SHORT).show();
//                    finish();
                }
                break;
        }
    }

    /*打開相機*/
    public void openCamera(Activity activity) {
        //獲取系統版本
        int currentApiVersion = Build.VERSION.SDK_INT;
        // 激活相機
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判斷存儲卡是否可以用，可用進行存儲
        if (hasSdcard()) {
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            String filename = timeStampFormat.format(new Date());
            newFile = new File(Environment.getExternalStorageDirectory(), filename + ".jpg");
            if (currentApiVersion < 24) {
                // 從文件中創建uri
                imageUri = Uri.fromFile(newFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, newFile.getAbsolutePath());
                //檢查是否有存儲權限，以免崩潰
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申請WRITE_EXTERNAL_STORAGE權限
                    Toast.makeText(this, "請開啓存儲權限", Toast.LENGTH_SHORT).show();
                    return;
                }
                imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            }
        }
        // 開啓一個帶有返回值的Activity，請求碼爲PHOTO_REQUEST_CAMERA
        activity.startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
    }


    /*
     * 判斷sdcard是否被掛載
     */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /*頁面回調*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        //Log.e(TAG, "onActivityResult: " + data);
        switch (requestCode) {
            case Constant.REQ_QR_CODE:
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    addGoodsBarcodeEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    getGoodName(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                }
                break;
            case 100:
                if (data != null) {
                    addGoodsClassificationName.setText(data.getStringExtra("name"));
                    classId = data.getStringExtra("id");
                }
                break;

            //byron
            case PHOTO_REQUEST_CAMERA:
                //Log.e(TAG, "takePhoto: 7");
                if (resultCode == RESULT_OK) {
//                    String imagePath = getImagePath(imageUri, null);
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        //-------------------------------圖片展示-----------------------
                        goodsPicture.setImageBitmap(bitmap);
                        Log.e(TAG, "onActivityResult: =====================");

                        String FILE_PATH = "/sdcard/syscamera.jpg";
//                        ByteArrayOutputStream outs;
                        Bitmap tu;
                        tu = BitmapCompressor.compressBitmap(bitmap, 1024);
//                        outs = new ByteArrayOutputStream();
//                        tu.compress(Bitmap.CompressFormat.JPEG, 50, outs);
//                        byte[] images = outs.toByteArray();
//                        if (!(images.length > (1000 * 1024 * 1))) {
                        //文件
                        newFile = saveBitmapFile(tu, FILE_PATH);
                        upLoad();
//                        } else {
//                            Toast.makeText(context, "圖片過大", Toast.LENGTH_SHORT).show();
//                        }

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //判斷手機系統版本號
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4及以上系統使用這個方法處理圖片
                        handleImageOnKitKat(data);
                    } else {
                        //4.4一下系統使用這個方法處理圖片
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
        }

    }

    /**
     * 把bitmap 轉file
     *
     * @param bitmap
     * @param filepath
     */
    public static File saveBitmapFile(Bitmap bitmap, String filepath) {
        File file = new File(filepath);//將要保存圖片的路徑
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果是document類型的Uri，則通過document id處理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; //解析數字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content類型的Uri，則使用普通方式處理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file類型的Uri,直接獲取圖片路徑即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根據獲取圖片路徑顯示圖片
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通過Uri和selection來獲取真是的圖片路徑
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /*顯示圖片並上傳*/
    private void displayImage(String imagePath) {
        filePath = imagePath;

        Log.e(TAG, "displayImage: 選擇的圖片的路徑=" + imagePath);
        if (imagePath != null) {
            ByteArrayOutputStream outs;
            Bitmap tu;
            tu = BitmapCompressor.decodeSampledBitmapFromFile(filePath, 720, 1280);
            outs = new ByteArrayOutputStream();
            tu.compress(Bitmap.CompressFormat.JPEG, 50, outs);
            byte[] images = outs.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            goodsPicture.setImageBitmap(bitmap);
//            File chooseFile = new File(imagePath);
//            newFile = chooseFile;
            if (!(images.length > (1000 * 1024 * 1))) {
                //文件
                newFile = saveBitmapFile(tu, filePath);
                upLoad();
            } else {
                Toast.makeText(context, "圖片過大", Toast.LENGTH_SHORT).show();
            }
            //獲取的圖片
        } else {
//            Toast.makeText(context, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }

    /*獲取商品名稱*/
    private void getGoodName(String code) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("code", code);
            HttpUtils.post(context, Common.GET_GOOD_NAME, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            addGoodsName.setText(json.getJSONObject("data").getString("name"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*獲取商品規格*/
    private void getSkuList() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            HttpUtils.post(context, Common.SKU_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    skuInfo = GsonUtils.JsonToBean(text, SkuInfo.class);
                    Message msg = new Message();
                    if (skuInfo.getStatus() == 1) {
                        msg.what = 3;
                    } else {
                        msg.what = 4;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*設置輸入框只能輸入兩位小數*/
    private void setEdit(final EditText edit) {
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains(".")) {
                    if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 2) {
                        charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 3);
                        edit.setText(charSequence);
                        edit.setSelection(charSequence.length());
                    }
                }
                if (charSequence.toString().trim().substring(0).equals(".")) {
                    charSequence = "0" + charSequence;
                    edit.setText(charSequence);
                    edit.setSelection(2);
                }

                if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
                    if (!charSequence.toString().substring(1, 2).equals(".")) {
                        edit.setText(charSequence.subSequence(1, 2));
                        edit.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
